package com.yunche.yunchebusiness.ui.view

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.yunche.yunchebusiness.R
import com.yunche.yunchebusiness.utils.ViewHelper
import org.jetbrains.anko.find


/**
 * Create by Crcker on 2018/11/12 10:56
 * Email: Crcker@163.com
 */


class YuncheToolBar(context: Context, attributes: AttributeSet) : RelativeLayout(context, attributes),
    View.OnClickListener {

    var yuncheToolbarCallBack: YuncheToolbarCallBack? = null

    init {
        LayoutInflater.from(context).inflate(R.layout.layout_yunche_toolbar_item, this, true)
        var tv_yunchebar_title = find<TextView>(R.id.tv_yunchebar_title)
        var tv_yunchebar_right = find<TextView>(R.id.tv_yunchebar_right)
        var attr = context.obtainStyledAttributes(attributes, R.styleable.YuncheToolBar)
        var title = attr.getString(R.styleable.YuncheToolBar_YuncheBarTitle)
        var rightTitle = attr.getString(R.styleable.YuncheToolBar_YuncheBarRightTitle)
        var showBack = attr.getBoolean(R.styleable.YuncheToolBar_YuncheToolBarShowBack, true)
        var sourceId = attr.getResourceId(R.styleable.YuncheToolBar_YuncheBarRightSrc, -1)
        tv_yunchebar_title.text = title
        tv_yunchebar_right.text = rightTitle

        if (sourceId != -1) {
            tv_yunchebar_right.setCompoundDrawablesWithIntrinsicBounds(
                resources.getDrawable(sourceId),
                null,
                null,
                null
            )
            tv_yunchebar_right.compoundDrawablePadding = 4
        }

        var back = find<ImageView>(R.id.iv_yunche_toolbar)
        ViewHelper.setVisibility(showBack, back)
        back.setOnClickListener(this)
        tv_yunchebar_right.setOnClickListener(this)
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_yunche_toolbar -> {
                yuncheToolbarCallBack?.onBackClick()
                if(yuncheToolbarCallBack == null){
                    (context as Activity).finish()
                }
            }
            R.id.tv_yunchebar_right -> {
                yuncheToolbarCallBack?.onRightClick()
            }
        }
    }

    interface YuncheToolbarCallBack {
        fun onBackClick()

        fun onRightClick()
    }
}